<!-- templates/admin.html -->
<!DOCTYPE html>
<html>
<head>
    <title>地铁线路管理系统</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .section { margin-bottom: 30px; border: 1px solid #ddd; padding: 20px; border-radius: 5px; }
        table { width: 100%; border-collapse: collapse; margin: 10px 0; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
        input[type="text"], select { padding: 6px; width: 200px; }
        button { padding: 6px 12px; background-color: #4CAF50; color: white; border: none; border-radius: 4px; cursor: pointer; }
        button:hover { background-color: #45a049; }
        .result { background-color: #f8f9fa; padding: 15px; margin-top: 10px; }
        .time-input-group {
            margin: 15px 0;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .time-input-group h4 {
            margin: 0 0 10px 0;
            color: #666;
        }
        input[type="time"] {
            padding: 6px;
            margin-right: 10px;
        }
    </style>
</head>
<body>
    <h1>地铁线路管理系统</h1>

    <!-- 线路管理 -->
    <div class="section">
        <img src="{{ url_for('static', filename='map.png') }}" alt="地铁线路图" style="width: 100%;">
        <h2>线路列表</h2>
        <table id="linesTable">
            <thead>
                <tr>
                    <th>线路名称</th>
                    <th>环线</th>
                    <th>首班车</th>
                    <th>末班车</th>
                    <th>站点数量</th>
                    <th>类型</th>
                </tr>
            </thead>
            <tbody id="linesBody"></tbody>
        </table>

        <h3>添加新线路</h3>
        <form id="addLineForm">
            <input type="text" name="name" placeholder="线路名称" required>
            <input type="number" name="gap_time" placeholder="间隔时间(秒)" required>
            <input type="number" name="speed" placeholder="速度(m/s)" step="0.1" required>

            <div class="time-input-group">
                <h4>方向1时刻</h4>
                <input type="time" name="dir1_first" required>
                <input type="time" name="dir1_last" required>
            </div>

            <div class="time-input-group">
                <h4>方向2时刻</h4>
                <input type="time" name="dir2_first">
                <input type="time" name="dir2_last">
            </div>

            <button type="submit">添加线路</button>
        </form>

        <h3>删除线路</h3>
        <form id="delLineForm">
            <input type="text" name="line_name" placeholder="线路名称" required>
            <button type="submit">删除线路</button>
        </form>
    </div>

    <!-- 站点管理 -->
    <div class="section">
        <h2>站点管理</h2>

        <h3>添加站点</h3>
        <form id="addStationForm">
            <input type="text" name="line_name" placeholder="线路名称" required>
            <input type="text" name="station_name" placeholder="站点名称" required>
            <input type="text" name="front_station" placeholder="前一站名称" >
            <input type="number" name="distance" placeholder="距离(m)" required>
            <button type="submit">添加站点</button>
        </form>

        <h3>删除站点</h3>
        <form id="delStationForm">
            <input type="text" name="line_name" placeholder="线路名称" required>
            <input type="text" name="station_name" placeholder="站点名称" required>
            <button type="submit">删除站点</button>
        </form>
    </div>

    <!-- 路径测试 -->
    <div class="section">
        <h2>路径测试</h2>
        <form id="testForm">
            <input type="text" name="start" placeholder="出发站" required>
            <input type="text" name="end" placeholder="到达站" required>
            <button type="submit">测试路径</button>
        </form>
        <div id="testResult" class="result"></div>
    </div>


    <script>
        // 加载线路数据
        function loadLines() {
            fetch('/api/get/map')
                .then(res => res.json())
                .then(data => {
                    const tbody = document.getElementById('linesBody');
                    tbody.innerHTML = data.lines.map(line => `
                        <tr>
                            <td>${line.line_name}</td>
                            <td>${line.is_loop ? '是' : '否'}</td>
                            <td>${formatTime(line.dir1_first)}</td>
                            <td>${formatTime(line.dir1_last)}</td>
                            <td>${line.stations.length}</td>
                            <td><button onclick="deleteLine('${line.line_name}')">地铁</button></td>
                        </tr>
                    `).join('');
                });
        }

        // 表单处理
        function handleForm(formId, url, method='POST') {
            document.getElementById(formId).addEventListener('submit', async (e) => {
                e.preventDefault();
                const formData = new FormData(e.target);
                const data = Object.fromEntries(formData.entries());
                if(formId==='addLineForm'){
                    try {
                        const dir = [
                            timeToSeconds(data.dir1_first),
                            timeToSeconds(data.dir1_last),
                            data.dir2_first ? timeToSeconds(data.dir2_first) : 0,
                            data.dir2_last ? timeToSeconds(data.dir2_last) : 0
                        ];

                        const payload = {
                            name: data.name,
                            gap_time: data.gap_time,
                            speed: data.speed,
                            dir: dir
                        };

                        const res = await fetch(url, {
                            method,
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify(payload)
                        });

                        const result = await res.json();
                        alert(result.message || '操作成功');
                        loadLines();
                    } catch (err) {
                        alert('操作失败: ' + err.message);
                    }
                } else {
                    try {
                    const res = await fetch(url, {
                        method,
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(data)
                    });

                    const result = await res.json();
                    alert(result.message || '操作成功');
                    loadLines();
                    } catch (err) {
                        alert('操作失败: ' + err.message);
                    }
                }
            });
        }
        // 时间转换函数
        function timeToSeconds(timeStr) {
            if (!timeStr) return 0;
            const [hours, minutes] = timeStr.split(':').map(Number);
            if (hours < 0 || hours > 23 || minutes < 0 || minutes > 59) {
                throw new Error('无效时间格式');
            }
            return hours * 3600 + minutes * 60;
        }

        // 表格时间显示修改
        function formatTime(seconds) {
            if (!seconds) return '-';
            const date = new Date(seconds * 1000);
            return date.toISOString().substr(11, 5);
        }

        // 绑定表单
        handleForm('addLineForm', '/api/add/line');
        handleForm('delLineForm', '/api/del/line');
        handleForm('addStationForm', '/api/add/station');
        handleForm('delStationForm', '/api/del/station');

        // 路径测试
        document.getElementById('testForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = new FormData(e.target);
            const params = new URLSearchParams(formData);

            try {
                const res = await fetch(`/api/get/way?${params}`);
                const data = await res.json();
                showTestResult(data);
            } catch (err) {
                alert('测试失败: ' + err.message);
            }
        });

        // 显示测试结果
        function showTestResult(data) {
            const resultDiv = document.getElementById('testResult');
            resultDiv.innerHTML = data.plans ? data.plans.map(plan => `
                <h4>方案 (${plan.lines.join(' → ')})</h4>
                <table>
                    <tr><th>票价</th><th>距离</th><th>耗时</th><th>换乘</th></tr>
                    <tr>
                        <td>${calculateFare(plan.dist)}元</td>
                        <td>${(plan.dist/1000).toFixed(1)}公里</td>
                        <td>${Math.ceil(plan.whole_time/60)}分钟</td>
                        <td>${plan.trans_stations?.length || 0}次</td>
                    </tr>
                </table>
                <h5>详细路径：</h5>
                <div>${plan.visited_station.map(s => s.join(' → ')).join('<br>')}</div>
            `).join('<hr>') : data.message;
        }

        // 票价计算
        function calculateFare(distance) {
            const km = distance / 1000;
            if (km <= 6) return 3;
            if (km <= 12) return 4;
            if (km <= 22) return 5;
            if (km <= 32) return 6;
            return 6 + Math.ceil((km - 32) / 20);
        }

        // 初始化加载
        loadLines();
    </script>
</body>
</html>